#include <memory>

#include "TcpServer.hpp"
#include "Calculator.hpp"
using cal_fun = std::function<Response(const Request &req)>;
class Parse
{
public:
    Parse(cal_fun cal)
        : _cal(cal)
    {
    }
    std::string Entry(std::string &package)
    {
        std::string message;
        std::string respstr;
        while (Decode(package, &message)) // while循环一次处理多个报文
        {
            // 1.判断报文完整性
            LOG(Loglevel::DEBUG) << "Content: \n"
                                 << message;
            if (message.empty())
            {
                break;
            }

            // 2.反序列化 //message接收到的是一个序列化的Request字符串
            Request req;
            if (!req.Deserizlize(message))
                break;
            std::cout << "##############" << std::endl;
            req.Print();
            std::cout << "##############" << std::endl;
            // 3.计算结果
            Response resp = _cal(req);
            // 4.序列化
            std::string res;
            resp.Serizlize(res);
            LOG(Loglevel::DEBUG) << "序列化: \n"
                                 << res;
            // 5.添加报头
            Encode(res);
            LOG(Loglevel::DEBUG) << "Encode: \n"
                                 << res;
            // 6.拼接应答
            respstr += res;
        }
        LOG(Loglevel::DEBUG) << "resptr: \n"
                             << respstr;
        return respstr;
    }
    ~Parse()
    {
    }

private:
    cal_fun _cal;
};
int main()
{
    ENABLE_CONSOLE_LOG();
    // 计算模块
    Calculator mycal;

    // 解析模块
    Parse myparse([&mycal](const Request &req)
                  { return mycal.Excute(req); });
    // 网络通信模块 只负责IO
    std::unique_ptr<TcpServer> ser_ptr = std::make_unique<TcpServer>([&myparse](std::string &package)
                                                                     { return myparse.Entry(package); });
    ser_ptr->InitServer();
    ser_ptr->Start();
    return 0;
}